import React, { useEffect, useImperativeHandle, useState } from 'react';
import { Form, Field, Input, Tree } from '@alifd/next';
import { useFusionTable } from 'ahooks';
import store from '@/store';

const Operation = (props, ref) => {
  const { actionType, roleId } = props;
  const [menuIdList, setMenuIdList] = useState([]);
  const menuDispatchers = store.useModelDispatchers('menu');
  const roleState = store.useModelState('role');

  const { tableProps } = useFusionTable(menuDispatchers.treeAuthList, {});

  const field = Field.useField([]);
  useEffect(() => {
    field.reset();
    let newValues = {};
    if (roleId !== undefined) {
      if (roleState.one !== undefined) {
        const role = roleState.one;
        newValues = {
          roleId: role.roleId,
          roleName: role.roleName,
          remark: role.remark,
          menuIdList: role.menuIdList,
          createTime: role.createTime,
        };
        setMenuIdList(role.menuIdList.map(String));
      }
    }
    field.setValues(newValues);
  }, [field, roleId, roleState.one]);
  useImperativeHandle(ref, () => {
    return {
      getValues(callback) {
        field.validate((errors, values) => {
          if (errors) {
            return;
          }

          callback(values);
        });
      },
    };
  });
  const isPreview = actionType === 'preview';

  return (
    <>
      <Form fullWidth useLabelForErrorMessage field={field} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <Form.Item label="角色名称" isPreview={isPreview} required>
          <Input name="roleName" />
        </Form.Item>
        <Form.Item label="备注" isPreview={isPreview}>
          <Input name="remark" />
        </Form.Item>
        <Form.Item label="授权">
          {isPreview ? null : <Input htmlType="hidden" name="menuIdList" value={menuIdList.join(',')} />}
          <Tree
            checkable
            showLine
            defaultExpandAll
            checkedKeys={menuIdList}
            onCheck={(keys) => setMenuIdList(keys)}
            dataSource={tableProps.dataSource}
          />
        </Form.Item>
        {isPreview ? (
          <Form.Item label="创建时间" isPreview>
            <Input name="createTime" />
          </Form.Item>
        ) : null}
      </Form>
    </>
  );
};

export default React.forwardRef(Operation);
